package com.guyaogg.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.guyaogg.common.to.mq.SeckillOrderTo;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.vo.MemberRespVO;
import com.guyaogg.gulimall.seckill.feign.CouponFeignService;
import com.guyaogg.gulimall.seckill.feign.ProductFeignService;
import com.guyaogg.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.guyaogg.gulimall.seckill.service.SeckillService;
import com.guyaogg.gulimall.seckill.to.SeckillSkuRedisTo;
import com.guyaogg.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.guyaogg.gulimall.seckill.vo.SkuInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author 顾遥
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    /**
     * +商品随机码
     */
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.扫描最近三天需要参与的秒杀活动
        R session = couponFeignService.getLatest3DaySession();
        if (session.getCode() == 0) {
            // 上架商品
            List<SeckillSessionWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            // 缓存到 Redis
            // 1.缓存活动信息
            saveSessionInfos(sessionData);
            // 2.缓存活动的关联商品的信息
            saveSessionSkuInfo(sessionData);

        }

    }

    /**
     * // 返回当前时间可以参加的秒杀商品信息
     *
     * @return 返回当前时间可以参加的秒杀商品信息
     */
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // 1.确定当前时间属于哪个秒杀场次
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        if (keys == null) {
            return null;
        }
        long time = System.currentTimeMillis();
        for (String key : keys) {
            // seckill:sessions:1635645600000_1635649200000
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                // 2.获取这个秒杀需要的所有秒杀商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = null;
                if (range != null) {
                    list = hashOps.multiGet(range);
                }
                if (list != null) {
                    return list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
//                        redisTo.setRandomCode(null); 当前秒杀开始了，需要随机码
                        return redisTo;
                    }).collect(Collectors.toList());
                }
                break;
            }
        }
        return null;


    }

    @Override
    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        // 1.找到所有需要参与秒杀的商品 key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        // TODO 秒杀场数多次,,,redis过期删除？？
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {

                    String json = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                    if (redisTo != null) {
                        long current = System.currentTimeMillis();
                        if (current < redisTo.getStartTime() || current > redisTo.getEndTime()) {
                            redisTo.setRandomCode(null);
                        }
                        log.debug("获取秒杀：{}", redisTo);
                        return redisTo;
                    }

                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVO memberRespVO = LoginUserInterceptor.loginUser.get();

        // 1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
        // 2.校验合法性
        long startTime = redisTo.getStartTime();
        long endTime = redisTo.getEndTime();
        long current = System.currentTimeMillis();
        long ttl = endTime - startTime;
        // 时间
        if (current < startTime || current > endTime) {
            return null;
        }
        String randomCode = redisTo.getRandomCode();
        String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
        // 随机码和商品 id
        if (!randomCode.equals(key) || !killId.equals(skuId)) {
            return null;
        }
        // 购买商品是否合理
        if (num > redisTo.getSeckillLimit().intValue()) {
            return null;
        }
        // 验证这个人是否购买过，幂等性，如果秒杀成功就展位,自动过期
        String redisKey = memberRespVO.getId() + "_" + skuId;
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
        if (Boolean.FALSE.equals(aBoolean)) {
            // 展位失败
            return null;
        }
        // 尝试获取信号量
        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
        try {
            boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
            if(!b){
                return null;
            }
            // 秒杀成功
            // 快速下单,发送 MQ 消息
            String orderSn = IdWorker.getTimeId();
            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
            seckillOrderTo.setOrderSn(orderSn);
            seckillOrderTo.setNum(num);
            seckillOrderTo.setMemberId(memberRespVO.getId());
            seckillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
            seckillOrderTo.setSkuId(redisTo.getSkuId());
            seckillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
            rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order",seckillOrderTo);
            return orderSn;

        } catch (InterruptedException e) {
            return null;
        }


    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessions) {
        sessions.forEach(session -> {
            long start = session.getStartTime().getTime();
            long end = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + start + "_" + end;
            if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
                // 幂等性，保证
                return;
            }
            List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
            // 缓存活动信息

            redisTemplate.opsForList().leftPushAll(key, collect);

        });
    }

    private void saveSessionSkuInfo(List<SeckillSessionWithSkus> sessions) {
        sessions.forEach(session -> {
            // 准备 hash 操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().forEach(seckillSkuVO -> {
                String key = seckillSkuVO.getPromotionSessionId() + "_" + seckillSkuVO.getSkuId().toString();
                if (Boolean.TRUE.equals(ops.hasKey(key))) {
                    // 幂等性，保证
                    return;
                }
                // 缓存商品
                SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                // 1.sku 的基本信息
                R r = productFeignService.getSkuInfo(seckillSkuVO.getSkuId());
                if (r.getCode() == 0) {
                    SkuInfoVO skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                    });
                    redisTo.setSkuInfo(skuInfo);
                }
                // 2.sku 的秒杀信息
                BeanUtils.copyProperties(seckillSkuVO, redisTo);
                // 3.设置上当前商品秒杀时间信息
                redisTo.setStartTime(session.getStartTime().getTime());
                redisTo.setEndTime(session.getEndTime().getTime());
                // 4.商品的随机码?(防止秒杀被机器强
                String token = UUID.randomUUID().toString().replace("-", "");
                redisTo.setRandomCode(token);
                String semaphoreKey = SKU_STOCK_SEMAPHORE + token;
                // 5.准备库存（信号量,作用限流
                RSemaphore semaphore = redissonClient.getSemaphore(semaphoreKey);
                semaphore.trySetPermits(seckillSkuVO.getSeckillCount().intValue());

                String jsonString = JSON.toJSONString(redisTo);
                ops.put(key, jsonString);
            });
        });
    }
}
